package com.th.supcom.pds.drugsupply.client.widget;

import java.util.ArrayList;
import java.util.List;

import net.carefx.framework.container.client.context.AppContext;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.data.BasePagingLoader;
import com.extjs.gxt.ui.client.data.Loader;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.EditorGrid;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.th.supcom.framework.dict.web.gwt.client.DictComboBox;
import com.th.supcom.framework.dict.web.gwt.client.model.DictModel;
import com.th.supcom.pds.common.client.commom.PdsAuditPrescServiceFactory;
import com.th.supcom.pds.common.utils.ClientUtils;
import com.th.supcom.pds.drugsupply.client.model.DrugInfoModel;
import com.th.supcom.pds.drugsupply.client.model.DrugSearchModel;

/**
 * 药品属性信息表格
 * 
 * @author zli
 */
public class DrugMaintainEditorGridPanel extends ContentPanel
{
    /** 公司版权信息. */
    public static final String copyright = "Copyright 2014, XuNuo Corporation";

    /** 每页分页数据条数. */
    private static final int s_LIMIT = Integer.MAX_VALUE;
    /** 提交路径. */
    public static final String SCC_BRANCH = "$URL$";

    /** 提交日期. */
    public static final String SCC_LAST_MODIFICATION_DATE = "$Date$";

    /** 最终修改人员. */
    public static final String SCC_LAST_MODIFIER_NAME = "$Author$";

    /** 最终版本号. */
    public static final String SCC_REVISION = "$Revision$";

    /** 定义储器. */
    private ListStore <DrugInfoModel> m_drugMaintainStore;

    /** 定义表. */
    private EditorGrid <DrugInfoModel> m_grid;

    /** 库存定义分页加载器. */
    private BasePagingLoader <PagingLoadResult <DrugInfoModel>> m_pagingLoad;

    private DrugSearchModel m_searchModel = new DrugSearchModel ();
    String deptCode = ClientUtils.getOrgModel().getOrgCode();

    public DrugMaintainEditorGridPanel ()
    {
        init ();
        loadGridData ();
    }

    private ColumnModel createGridHeader ()
    {
        final List <ColumnConfig> columns = new ArrayList <ColumnConfig> ();
        final ColumnConfig column1 = new ColumnConfig ();
        column1.setId ("phamName");
        column1.setHeader ("药品名称");
        column1.setWidth (220);
        column1.setEditor (getEditor3 ());
        column1.setAlignment (HorizontalAlignment.LEFT);
        columns.add (column1);
        ColumnConfig column = new ColumnConfig ();
        column.setId ("phamStdCode");
        column.setHeader ("药品编码");
        column.setAlignment (HorizontalAlignment.LEFT);
        column.setWidth (100);
        columns.add (column);
        column = new ColumnConfig ();
        column.setId ("phamSpec");
        column.setHeader ("药品规格");
        column.setWidth (100);
        column.setAlignment (HorizontalAlignment.LEFT);
        columns.add (column);

        column = new ColumnConfig ();
        column.setId ("packageSpec");
        column.setHeader ("零包规格");
        column.setRenderer (new GridCellRenderer <DrugInfoModel> ()
        {

            @Override
            public Object render (final DrugInfoModel model, final String property, final ColumnData config, final int rowIndex, final int colIndex,
                                  final ListStore <DrugInfoModel> store, final Grid <DrugInfoModel> grid)
            {
                final String name = model.getPackageFactor () + model.getPhamUnitName () + "/" + model.getPackageUnitName ();
                if (model.getPackageFactor () == null)
                {
                    return "";
                }
                return name;

            }
        });
        column.setWidth (100);
        column.setAlignment (HorizontalAlignment.LEFT);
        columns.add (column);

        column = new ColumnConfig ();
        column.setId ("retailPrice");
        column.setHeader ("零售价");
        column.setWidth (50);
        column.setAlignment (HorizontalAlignment.LEFT);
        column.setRenderer (ClientUtils.getRenderer ("retailPrice"));
        columns.add (column);

        column = new ColumnConfig ();
        column.setHeader ("供药");
        column.setId ("supplyIndicatorName");
        column.setWidth (50);
        column.setAlignment (HorizontalAlignment.LEFT);
        column.setEditor (getEditor (new DictComboBox ("DMS0011"), "supplyIndicator", "1", "是"));
        column.setRenderer (renderDefaultValue ("是"));
        column.setStyle ("background-color:#E6E6F2;");
        columns.add (column);

        column = new ColumnConfig ();
        column.setId ("expensiveName");
        column.setHeader ("贵重药品");
        column.setAlignment (HorizontalAlignment.LEFT);
        column.setWidth (65);
        column.setStyle ("background-color:#E6E6F2;");
        column.setEditor (getEditor (new DictComboBox ("DMS0011"), "expensive", "0", "否"));
        column.setRenderer (renderDefaultValue ("否"));
        columns.add (column);

        column = new ColumnConfig ();
        column.setId ("putDrugModeName");
        column.setHeader ("摆药属性");
        column.setAlignment (HorizontalAlignment.LEFT);
        column.setEditor (getEditor (new DictComboBox ("PDS0001"), "putDrugMode", "1", "人工摆药"));
        column.setRenderer (renderDefaultValue ("人工摆药"));
        column.setStyle ("background-color:#E6E6F2;");
        column.setWidth (68);
        columns.add (column);

        column = new ColumnConfig ();
        column.setId ("svrModeTypeName");
        column.setHeader ("发药方式");
        column.setAlignment (HorizontalAlignment.LEFT);
        column.setWidth (68);
        column.setStyle ("background-color:#E6E6F2;");
        column.setEditor (getEditor (new DictComboBox ("DMS0009"), "svrModeTypeId", "1", "领药类"));
        column.setRenderer (renderDefaultValue ("领药类"));
        columns.add (column);

        return new ColumnModel (columns);
    }

    private CellEditor getEditor (final DictComboBox combo, final String property, final String defaultCode, final String defaultValue)
    {
        final CellEditor editor = new CellEditor (combo)
        {
            @Override
            public Object postProcessValue (final Object value)
            {
                m_grid.getStore ().getAt (super.row).set (property, combo.getValue ().getDictItemCode ());
                return combo.getValue ().getDictItemName ();
            }

            @Override
            public Object preProcessValue (final Object value)
            {
                if (value == null)
                {
                    final DictModel model = new DictModel ();
                    model.setDictItemCode (defaultCode);
                    model.setDictItemName (defaultValue);
                    return model;
                }
                DictModel dictModel = null;
                for (final DictModel dict : combo.getStore ().getModels ())
                {
                    if (dict.getDictItemName ().equals (value.toString ()))
                    {
                        dictModel = dict;
                        break;
                    }
                }
                combo.setEditable (false);
                return dictModel;

            }
        };

        return editor;
    }

    private CellEditor getEditor3 ()
    {
        final DrugComboBoxForM check = new DrugComboBoxForM (new IExcuteQuery ()
        {

            @Override
            public void query (final PagingLoadConfig config, final String queryCondition, String deptCode, final AsyncCallback <PagingLoadResult <DrugInfoModel>> callback)
            {
                PdsAuditPrescServiceFactory.getPdsPropertyMaintainService ().searchPhamBasicInfoListWithPagingByName (config, queryCondition, deptCode, callback);
            }
        }, deptCode);
        final CellEditor editor = new CellEditor (check)
        {
            @Override
            public Object postProcessValue (final Object value)
            {
                if (value == null)
                {
                    return value;
                }
                return check.getValue ().getPhamName ();
            }

            @Override
            public Object preProcessValue (final Object value)
            {
                if (value == null)
                {
                    return value;
                }
                return check.getValue ();
            }
        };
        check.setAllowBlank (false);
        check.addSelectionChangedListener (new SelectionChangedListener <DrugInfoModel> ()
        {

            @Override
            public void selectionChanged (final SelectionChangedEvent <DrugInfoModel> se)
            {
                if (se.getSelectedItem () == null)
                {
                    return;
                }
                m_grid.getSelectionModel ().getSelectedItem ().setPhamStdCode (se.getSelectedItem ().getPhamStdCode ());
                m_grid.getSelectionModel ().getSelectedItem ().setPhamSpec (se.getSelectedItem ().getPhamSpec ());
                m_grid.getSelectionModel ().getSelectedItem ().setUnit (se.getSelectedItem ().getUnit ());
                m_grid.getSelectionModel ().getSelectedItem ().setRetailPrice (se.getSelectedItem ().getRetailPrice ());
                m_grid.getSelectionModel ().getSelectedItem ().setAllocation (se.getSelectedItem ().getAllocation ());
                m_grid.getSelectionModel ().getSelectedItem ().setPackageFactor (se.getSelectedItem ().getPackageFactor ());
                m_grid.getSelectionModel ().getSelectedItem ().setPhamUnitName (se.getSelectedItem ().getPhamUnitName ());
                m_grid.getSelectionModel ().getSelectedItem ().setPackageUnitName (se.getSelectedItem ().getPackageUnitName ());

            }
        });
        return editor;
    }

    public ListStore <DrugInfoModel> getListStore ()
    {
        return this.m_drugMaintainStore;
    }

    private void init ()
    {
        DrugMaintainPanelToolBar drugMaintainPanelToolBar;
        // 初始化中心面板
        setHeaderVisible (false);
        setLayout (new FitLayout ());
        m_searchModel.setOrgId (deptCode);
        m_grid = this.initdrugMaintain ();
        m_grid.addListener (Events.BeforeEdit, new Listener <GridEvent <DrugInfoModel>> ()
        {
            @Override
            public void handleEvent (final GridEvent <DrugInfoModel> be)
            {
                final DrugInfoModel drugInfoModel = be.getModel ();
                if (0 == be.getColIndex () && drugInfoModel.get ("flag") == null)
                {
                    be.setCancelled (true);
                    return;
                }

            }

        });

        drugMaintainPanelToolBar = new DrugMaintainPanelToolBar ();
        add (m_grid);
        setTopComponent (drugMaintainPanelToolBar);
    }

    private EditorGrid <DrugInfoModel> initdrugMaintain ()
    {
        final EditorGrid <DrugInfoModel> grid = new EditorGrid <DrugInfoModel> (initStore (), createGridHeader ());
        grid.setColumnReordering (true);
        grid.setStyleAttribute ("border", "0px");
        grid.setColumnLines (true);
        grid.setStripeRows (true);
        return grid;
    }

    /**
     * 初始化分页加载器.
     * 
     */
    private void initPagingLoad (final RpcProxy <PagingLoadResult <DrugInfoModel>> proxy)
    {
        m_pagingLoad = new BasePagingLoader <PagingLoadResult <DrugInfoModel>> (proxy);
        m_pagingLoad.setRemoteSort (true);
    }

    private ListStore <DrugInfoModel> initStore ()
    {
        final RpcProxy <PagingLoadResult <DrugInfoModel>> proxy = new RpcProxy <PagingLoadResult <DrugInfoModel>> ()
        {

            @Override
            protected void load (final Object loadConfig, final AsyncCallback <PagingLoadResult <DrugInfoModel>> callback)
            {
                PdsAuditPrescServiceFactory.getPdsPropertyMaintainService ().getPhamBasicInfoListWithPaging ((PagingLoadConfig) loadConfig, m_searchModel, callback);

            }
        };

        this.initPagingLoad (proxy);
        m_drugMaintainStore = new ListStore <DrugInfoModel> (m_pagingLoad);

        return m_drugMaintainStore;

    }

    /**
     * 加载数据.
     */
    public final void loadGridData ()
    {
        mask ("加载中");
        m_pagingLoad.load (0, DrugMaintainEditorGridPanel.s_LIMIT);
        m_pagingLoad.addListener (Loader.Load, new Listener <BaseEvent> ()
        {
            @Override
            public void handleEvent (final BaseEvent be)
            {
                unmask ();
            }
        });
    }

    /**
     * 刷新表格信息.
     */
    public void refreshdrugMaintainGridData ()
    {
        loadGridData ();
    }

    /**
     * 设置默认值渲染
     * 
     * @return add by Zli
     */
    private GridCellRenderer <DrugInfoModel> renderDefaultValue (final String defaultValue)
    {
        return new GridCellRenderer <DrugInfoModel> ()
        {

            @Override
            public Object render (final DrugInfoModel model, final String property, final ColumnData config, final int rowIndex, final int colIndex,
                                  final ListStore <DrugInfoModel> store, final Grid <DrugInfoModel> grid)
            {

                return model.get (property) == null ? defaultValue : model.get (property);

            }
        };
    }

    public void setSearchModel (DrugSearchModel searchModel)
    {
        DrugSearchModel dsm = searchModel;
        if (dsm == null)
        {
            dsm = new DrugSearchModel ();
            dsm.setOrgId (deptCode);
        }
        dsm.setOrgId (deptCode);
        m_searchModel = dsm;
    }

    public EditorGrid <DrugInfoModel> getGrid ()
    {

        return m_grid;
    }

}
